package com.biz.primus.ms.commodity.dao.redis;

import com.biz.primus.base.redis.CrudRedisDao;
import com.biz.primus.base.redis.util.RedisUtil;
import com.biz.primus.ms.commodity.dao.ro.ProductCascadeRo;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Set;

/**
 * 关联商品RedisDao
 *
 * @author david-liu
 * @date 2016年08月18日
 * @reviewer
 * @see
 */
@Repository
public class ProductCascadeRedisDao extends CrudRedisDao<ProductCascadeRo, Long> {

    @Autowired
    private ProductCascadeItemRedisDao productCascadeItemRedisDao;

    @Override
    public void save(ProductCascadeRo ro) {
        super.save(ro);
    }


    /**
     * 根据商品ID获取关联商品
     *
     * @param productId 商品ID
     * @return 关联商品
     */
    public List<ProductCascadeRo> findProductCascade(Long productId) {
        String key = getProductProductCascadeStringKey(productId);
        final Set<byte[]> bytes = zRange(key, 0, -1);
        if(CollectionUtils.isNotEmpty(bytes)){
            return this.findByIds(RedisUtil.bytesSetToLongList(bytes));
        }
        return Lists.newArrayList();
    }


    /**
     *  @Author: mounan
     *  @Description: 删除商品对应的所有配置和所有的属性明细
     *  @param:
     *  @Date: 2017/6/17
     */
    public void deleteAll(Long productId) {
        final String key = this.getProductProductCascadeStringKey(productId);
        final Set<byte[]> bytes = zRange(key, 0, - 1);
        if(CollectionUtils.isNotEmpty(bytes)){
            List<Long> ids = RedisUtil.bytesSetToLongList(bytes);
            for (Long id : ids) {
                delete(id);
            }
        }
        zremrangeByRank(key, 0, -1);
    }

    /**
     * 获取关联商品StringKey (商品ID --> ProductCascadeId)
     *
     * @param productId 商品ID
     * @return StringKey
     */
    private String getProductProductCascadeStringKey(Long productId) {
        return getKeyByParams("productCascadeId", productId);
    }


    public void delete(List<ProductCascadeRo> existsProductCascadeRos) {
    }
}
